<?php
namespace app\admin\controller;
use think\Db;
use think\facade\Request;
class Shop extends Common
{
    public function initialize(){
        parent::initialize();
    }
    //商城列表
    public function index(){
        if(Request::isAjax()) {
            $key = input('post.key');
            $this->assign('testkey', $key);
            $page =input('page')?input('page'):1;
            $pageSize =input('limit')?input('limit'):config('pageSize');
            $list = Db::table(config('database.prefix') . 'shop')
                ->where('name', 'like', "%" . $key . "%")
                ->order('id')
                ->paginate(array('list_rows'=>$pageSize,'page'=>$page))
                ->toArray();
            foreach ($list['data'] as $k=>$v){
                $list['data'][$k]['addtime'] = date('Y-m-d H:i',$v['addtime']);
                $urlapi[$k]=url('pay/index/index',['appid'=>$v['appid'],'shopid'=>$v['id']]);
                $list['data'][$k]['urlapi']='<a href="'.$urlapi[$k].'" target="_blank">商户收银台</a>';
                //余额
                if($v['level'] == 2){
                    $money = db('channel_order')->where('state',2)->where('sagentid',$v['id'])->sum('fei_sagent');
                    $cash=db('bill')->where(array('type'=>'shop','typeid'=>$v['id']))->sum('cash');
                    $list['data'][$k]['balance'] = number_format($money-$cash, 2);
                }else{
                    $t_money=db('channel_order')->where(array('shopid'=>$v['id'],'state'=>2))->sum('money');
                    $s_money=db('channel_order')->where(array('shopid'=>$v['id'],'state'=>2))->sum('fei_shop');
                    $s_cash=db('bill')->where(array('typeid'=>$v['id']))->sum('cash');
                    $list['data'][$k]['balance'] = number_format($t_money-$s_money-$s_cash,2);
                }
                
            }
            return $result = ['code'=>0,'msg'=>'获取成功!','data'=>$list['data'],'count'=>$list['total'],'rel'=>1];
        }
        $shoplist = cache('shoplist');
        if(!$shoplist){
            $shoplist=db('shop')->where('open',1)->order('id')->select();
            cache('shoplist',$shoplist);
        }
        return $this->fetch();
    }
    public function add(){
        if(Request::isAjax()) {
            //构建数组
            $data = Request::except('file');
            $data['addtime'] = time();
            $data['appid'] = rand_string(8,1);             
            $data['appkey'] = rand_string(24,5);
            if(empty($data['password'])){
                $data['password'] = md5($data['mobile']);
            }else{
                $data['password'] = md5($data['password']);
            }
            if(empty($data['paypwd'])){
                $data['paypwd'] = md5('123456');
            }else{
                $data['paypwd'] = md5($data['paypwd']);
            }
            $remobile = db('shop')->where('mobile',trim($data['mobile']))->find();
            if($remobile){
                $this->error('手机号重复!','index');
            }
            $data['level'] = explode(':', $data['level'])[1];
            db('shop')->insert($data);
            $result['code'] = 1;
            $result['msg'] = '添加成功!';
            cache('shoplist', NULL);
            $result['url'] = url('index');
            return $result;
        }else{  
            $this->assign('title',lang('add').'商城'); 
            $this->assign('cionlist',cache('cionlist'));  
            $this->assign('info','null'); 
            $this->assign('selectcion','null');
            return $this->fetch('form');
        }
    }
    public function edit(){
        if(Request::isAjax()) { 
            $data = Request::except('file');    
            if(empty($data['password'])){
                unset($data['password']);
            }else{
                $data['password'] = md5($data['password']);
            }
            if(empty($data['paypwd'])){
                unset($data['paypwd']);
            }else{
                $data['paypwd'] = md5($data['paypwd']);
            }
            $data['level'] = explode(':', $data['level'])[1];
            if($data['level'] == 2){
               $data['agentid'] = '';  
            }
            db('shop')->update($data);
            $result['code'] = 1;
            $result['msg'] = '修改成功!';
            cache('shoplist', NULL);
            $result['url'] = url('index');
            return $result;
        }else{
            $id=input('id');
            $Info=db('shop')->where(array('id'=>$id))->find();
            $this->assign('info',json_encode($Info,true));
            $selectcion =explode(',',$Info['cions']);
            $this->assign('selectcion',json_encode($selectcion,true));
            $this->assign('cionlist',cache('cionlist')); 
            $this->assign('title',lang('edit').'商城');
            return $this->fetch('form');
        }
    }
    //设置状态
    public function editState(){  
        if(db('shop')->where(array('id'=>input('id')))->update(array('open'=>input('open')))!==false){
            cache('shoplist', NULL);
            return ['status'=>1,'msg'=>'设置成功!'];
        }else{
            return ['status'=>0,'msg'=>'设置失败!'];
        }
    } 
    public function del(){
        db('shop')->where(array('id'=>input('id')))->delete();
        cache('shoplist', NULL);
        return ['code'=>1,'msg'=>'删除成功！'];
    } 

    /***************************代币管理*****************************/
    public function cion(){
        if(Request::isAjax()) {
            $key = input('key');
            $this->assign('testkey', $key);
            $list = db('shop_cion')->where('name|name_en', 'like', "%" . $key . "%")->order('id')->select(); 
            return $result = ['code'=>0,'msg'=>'获取成功!','data'=>$list,'rel'=>1];
        }
        $cionlist = cache('cionlist');
        if(!$cionlist){
            $cionlist=db('shop_cion')->where('open',1)->order('id')->select();
            cache('cionlist',$cionlist);
        }
        return $this->fetch();
    } 
    public function addCion(){
        if(Request::isAjax()) {
            db('shop_cion')->insert(input('post.'));
            $result['code'] = 1;
            $result['msg'] = '添加成功!';
            $result['url'] = url('cion');
            cache('cionlist', NULL);
            return $result;
        }else{
            $this->assign('title',lang('add').'新币种');
            $this->assign('info','null');
            return $this->fetch('cionform');
        }
    }
    public function editCion(){
        if(Request::isAjax()) { 
            db('channel')->where('cionid',input('post.id'))->update(array('price'=>input('post.price')));  
            db('shop_cion')->update(input('post.'));
            $result['code'] = 1;
            $result['msg'] = '修改成功!';
            $result['url'] = url('cion');
            cache('cionlist', NULL);
            return $result;
        }else{
            $id=input('param.id');
            $info=db('shop_cion')->where('id',$id)->find();
            $this->assign('title',lang('edit').'币种');
            $this->assign('info',json_encode($info,true));
            return $this->fetch('cionform');
        }
    }
    //设置状态
    public function editStateCion(){  
        if(db('shop_cion')->where(array('id'=>input('id')))->update(array('open'=>input('open')))!==false){
            cache('cionlist', NULL);
            return ['status'=>1,'msg'=>'设置成功!'];
        }else{
            return ['status'=>0,'msg'=>'设置失败!'];
        }
    }
    public function delCion(){
        $map['id'] = input('param.id');
        db('shop_cion')->where($map)->delete();
        cache('cionlist', NULL);
        return ['code'=>1,'msg'=>'删除成功！'];
    }  
    public function getCion(){
        $shop=db('shop')->where('id',input("shopid"))->value('cions');
        $map[] =array('id','in',$shop);
        $list=db('shop_cion')->where($map)->select();
        return $list;
    }

    //商户代理列表
    public function agent()
    {
        if(Request::isAjax()) {
            $key = input('post.key');
            $this->assign('testkey', $key);
            $page =input('page')?input('page'):1;
            $pageSize =input('limit')?input('limit'):config('pageSize');
            $list = Db::table(config('database.prefix') . 'shop')
                ->where('level',2)
                ->where('agentid','')
                ->where('name', 'like', "%" . $key . "%")
                ->order('id')
                ->paginate(array('list_rows'=>$pageSize,'page'=>$page))
                ->toArray();
            foreach ($list['data'] as $k=>$v){
                $list['data'][$k]['addtime'] = date('Y-m-d H:i:s',$v['addtime']);
                $money = db('channel_order')->where('state',2)->where('sagentid',$v['id'])->sum('fei_sagent');
                $cash=db('bill')->where(array('type'=>'shop','typeid'=>$v['id']))->sum('cash');
                $list['data'][$k]['balance'] = number_format($money-$cash, 2);
            }
            return $result = ['code'=>0,'msg'=>'获取成功!','data'=>$list['data'],'count'=>$list['total'],'rel'=>1];
        }
        return $this->fetch();
    }

    public function children_shop()
    {
        if(request()->isPost()){
            $agentid=input('post.agentid');
            $page =input('page')?input('page'):1;
            $pageSize =input('limit')?input('limit'):config('pageSize');
            $list=db('shop')
                ->alias('s')
                ->field('s.*,sa.name as agentname')
                ->join(config('database.prefix').'shop sa','sa.id = s.agentid','left')
                ->where('s.level','')
                ->where('s.agentid',$agentid)
                ->paginate(array('list_rows'=>$pageSize,'page'=>$page))
                ->toArray();
            foreach ($list['data'] as $k=>$v){
                $list['data'][$k]['addtime'] = date('Y-m-d H:i:s',$v['addtime']);
                
            }
            return $result = ['code'=>0,'msg'=>'获取成功!','data'=>$list['data'],'count'=>$list['total'],'rel'=>1];
        }
        $this->assign('agentid',input('agentid')); 
        return $this->fetch();
    }

}